import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.common.util.StreamUtil;
import com.boarsoft.message.bean.Message;
import com.boarsoft.message.core.MessageService;

public class SmsOutAdapter implements MessageService {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	protected String ip;
	protected int port;

	public void send(String text) throws Exception {
		// TODO 将报文直接发送到短信银行（实现简单中转）
		// String rs = SocketUtil.sendStr("10.0.192.189", 9000, text);
		String textGBK = new String(text.getBytes(), "UTF-8");
		// String rs = do9000("10.0.192.189", textGBK);//短信UATB
		String rs = do9000(ip, textGBK);// 短信UATB
		log.info("Response from SMS = {}", rs);
	}

	@Override
	public void put(Message msg) throws Exception {
		log.info("Send message {} to sms", msg.getAttachment());
		// // 通过Socket向短信银行发下行短信
		// String text = getContent_CCTZ();
		// // do9000(s);
		String text = msg.getAttachment().toString();
		this.send(text);
	}

	public String do9000(String ipAddress, String sendVal) throws UnknownHostException, IOException {
		Socket s = null;
		PrintWriter os = null;
		OutputStreamWriter osw = null;
		try {
			s = new Socket(ipAddress, port);
			osw = new OutputStreamWriter(s.getOutputStream(), "GBK");
			os = new PrintWriter(osw, true);
			os.println(sendVal);
			BufferedReader io = new BufferedReader(new InputStreamReader(s.getInputStream(), "GBK"));
			String rs = io.readLine();
			return rs;
			// } catch (Exception e) {
			// log.error("Error on write message to SMS", e);
		} finally {
			StreamUtil.close(os);
			try {
				if (s != null) {
					s.close();
				}
			} catch (Exception e) {
				log.error("Failed to close socket", e);
			}
		}
		// return null;
	}

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

}
